package com.example.demo.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.dao.ProductMapper;
import com.example.demo.model.ProductDO;
import com.example.demo.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 商品业务实现类
 */
@Service
public class ProductServiceImpl implements ProductService {

    @Autowired
    private ProductMapper productMapper;
    /**
     * 插入
     * @param productDO
     * @return
     */
    @Override
    public int insert(ProductDO productDO) {
        return productMapper.insert(productDO);
    }

    /**
     * 删除
     * @param id
     * @return
     */
    @Override
    @CacheEvict(value = "product", key = "#root.args[0]",beforeInvocation = true)
    public int delById(int id) {
        System.out.print("删除前");
        return productMapper.deleteById(id);

    }

    /**
     * 更新
     * @param productDO
     * @return
     */
    @Override
    @Caching(
        put = {
            @CachePut(value = "product",key = "#productDO.id"),
            @CachePut(value = "product",key = "#root.methodName + '_' + #productDO.id")
        }
    )
    public ProductDO updateById(ProductDO productDO) {
        productMapper.updateById(productDO);
        return productDO;
    }

    /**
     * 查询单条
     * @param id
     * @return
     */
    @Override
    @Cacheable(value = "product",key = "#id")
    public ProductDO getById(int id) {
        return productMapper.selectById(id);
    }

    /**
     * 查询，分页
     * @param pageNumber
     * @param pageSize
     * @return
     */
    @Override
    @Cacheable(value = "product_page",keyGenerator = "springCacheCustomKeyGenerator",cacheManager = "cacheManagerMinute")
    public Map<String, Object> getListPage(String pageNumber, String pageSize) {
        Page<ProductDO> page = new Page<>(Integer.parseInt(pageNumber), Integer.parseInt(pageSize));
        IPage<ProductDO> productDOPage = productMapper.selectPage(page, null);
        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("data",productDOPage.getRecords());
        resultMap.put("total",productDOPage.getTotal());
        resultMap.put("pageSize",productDOPage.getSize());
        return resultMap;
    }
}
